import {
  Controller,
  Post,
  Body,
  Res,
  UseInterceptors,
  HttpException,
  HttpStatus,
} from '@nestjs/common';
import { ApiBody, ApiOperation, ApiTags } from '@nestjs/swagger';
import { LoginService } from './login.service';
import { HttpReslut } from 'src/common/result/http-reslut';
import { User } from 'src/entities/user.entity';
import { Login } from './dto/login.dto';
import { JwtService } from '@nestjs/jwt';
import { Response } from 'express';

@ApiTags('登录')
@Controller('login')
export class LoginController {
  constructor(
    private readonly jwtService: JwtService,
    private readonly loginService: LoginService,
  ) {}

  @ApiOperation({
    summary: '用户登录',
  })
  @ApiBody({
    description: '用户登录模板数据',
    type: Login,
  })
  @Post()
  async login(@Body() login: Login, @Res({ passthrough: true }) res: Response) {
    let user: User = await this.loginService.login(login);
    if (!user) {
      throw new HttpException('用户名或密码错误', HttpStatus.BAD_REQUEST);
    }
    const access_token = this.jwtService.sign({ payload: user.id });
    res.setHeader('Access-Control-Expose-Headers', 'token');
    res.setHeader('token', access_token);
    return new HttpReslut<User>(user);
  }
}
